<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TemplateTree
 *
 * @author zelic
 */
class TemplateTree {

    var $treeName = "";
    var $variables;
    var $sections;
    var $imports;
    var $content;
    

    public function __construct($treeName = "") {
        $this->variables = array();
        $this->sections = array();
        $this->imports = array();
        $this->treeName = $treeName;
        $this->content = "";
    }

    public function setVariable($key, $value) {
        $this->variables[$key] = $value;
    }

    public function getVariable($key) {
        if (array_key_exists($key, $this->variables)) {
            return $this->variables[$key];
        }
        return false;
    }

    public function addSection($treeName) {
        $tree = new TemplateTree($treeName);
        $this->sections[] = $tree;
        return $tree;
    }
    
    public function import($templatePath, $templateName){
        if (file_exists($templatePath)&&$templateName!="") {
            $this->imports[$templateName]=  file_get_contents($templatePath);
        } else if (file_exists("../app/view/".$templatePath)&&$templateName!=""){
            $this->imports[$templateName]=  file_get_contents("../app/view/".$templatePath);
        }
    }


    public function render($parentContent) {
        $this->getContent($parentContent);
        
        foreach ($this->imports as $key=>$content){
            $im_pattern = "{{>$key}}";
            $this->content = ereg_replace($im_pattern, $content, $this->content);
        }
        
        foreach ($this->sections as $section) {
            $sec_pattern = "({{#$section->treeName}}.*{{/$section->treeName}})";
            $section->render($parentContent);
            
            $this->content = ereg_replace($sec_pattern, "$section->content\\1", $this->content);
            
        }
        
        foreach ($this->variables as $key=>$value) {
            $var_pattern = "{{".$key."}}";
            $this->content = ereg_replace($var_pattern, $value, $this->content);   
        }
        
        $this->removeTag();
    }

    public function getContent($parentContent) {
        if ($this->treeName == "") {
            $this->content = $parentContent;
        } else {
            $regs = array();
            $pattern = "{{#$this->treeName}}(.*){{/$this->treeName}}";
            ereg($pattern, $parentContent, $regs);
            $this->content = $regs[1];
        }
    }

    public function removeTag() {
        $rem_pattern = "({{#.*}}.*{{/.*}}|{{.*}}|{{>.*}})";
        $this->content = ereg_replace($rem_pattern, "", $this->content);
    }
    
    public function __toString() {
        return $this->content;
    }

}

?>
